#!/usr/bin/python
#coding:utf-8

###############################################################################################
##    从general log日志中提取某个线程执行的SQL                                                    ##
##    python3 get_thread_sql_generallog.py -f /data/mysql1/data/general.log -q 8055           ##
##                                                                                            ## 
################################################################################################

import re 
import argparse

def _argparse():
    "docstring for fn_argparse"
    parser = argparse.ArgumentParser(description="This is description")
    parser.add_argument('-f',action='store',
            dest='general_log',default='./mysql_general.log',help='MySQL general log name')
    parser.add_argument('-q',action='store',
        dest='query_thread_id',help='query thread id')
    return parser.parse_args()

def process_general_log(general_filename,query_id):
    pattern_date = r'^\d{4}-\d{2}-\d{2}T'
    pattern_id = str(query_id) + ' Query'
    in_block_flag = 0
    line_start_date_flag = 1
    with open(general_filename,'r',encoding='utf-8') as f:
        for line in f:
            if re.match(pattern_date,line):
                line_start_date_flag = 1
                if pattern_id in line:
                    in_block_flag = 1
                    print(line,end='')
                else:
                    in_block_flag = 0
            else:
                line_start_date_flag = 0
        
            if line_start_date_flag == 0 and in_block_flag == 1:
                line_start_date_flag = 1
                print(line,end='')

def main():
    parser = _argparse()
    general_filename = parser.general_log
    query_id = parser.query_thread_id

    process_general_log(general_filename,query_id)

if __name__ == '__main__':
    main()
